package com.wenshi.web.netty.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.*;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;


@Component
public class MqttClientHandler extends SimpleChannelInboundHandler<MqttMessage> {

    private int messageId = 1; // 消息 ID 从 1 开始
    private ChannelHandlerContext ctx;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;  // 保存最新的 ctx
        // 发送连接请求
        MqttConnectMessage connectMessage = MqttMessageBuilders.connect()
                .clientId("nettyClient")
                .keepAlive(60)
                .build();
        ctx.writeAndFlush(connectMessage);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) throws Exception {
        if (msg instanceof MqttConnAckMessage) {
            MqttConnAckMessage connAckMessage = (MqttConnAckMessage) msg;
            if (connAckMessage.variableHeader().connectReturnCode() == MqttConnectReturnCode.CONNECTION_ACCEPTED) {
                // 连接成功，订阅主题
                MqttSubscribeMessage subscribeMessage = MqttMessageBuilders.subscribe()
                        .messageId(1)
                        .addSubscription(MqttQoS.AT_LEAST_ONCE, "TT")
                        .build();
                ctx.writeAndFlush(subscribeMessage);
            }
        } else if (msg instanceof MqttPublishMessage) {
            // 接收发布消息
            MqttPublishMessage publishMessage = (MqttPublishMessage) msg;
            String payload = publishMessage.payload().toString(io.netty.util.CharsetUtil.UTF_8);
            System.out.println("Received message: " + payload);
            publishMsg();
        }else if (msg instanceof MqttPubAckMessage) {
            // 处理 PUBACK 确认
            System.out.println("Publish acknowledged.");
        }
    }

    public void publishMsg() {
        MqttPublishMessage publishMessage = MqttMessageBuilders.publish()
                .topicName("test")
                .payload(Unpooled.copiedBuffer("Hello, MQTT!", CharsetUtil.UTF_8))
                .qos(MqttQoS.AT_LEAST_ONCE)
                .messageId(messageId++) // 递增消息 ID
                .build();

        ctx.writeAndFlush(publishMessage);

    }
}
